<script setup>
// 引入接口
import { registerUser } from '@/api/user'
import { ElMessage } from 'element-plus';
import { ref } from "vue";
// 获取整个表单的信息
const form = ref()

// 登录表单填写的数据
const registerForm = ref({
  username: '',
  password: '',
  repassword: ''
})

const drawer = ref(true) // 控制抽屉是否显示

// 表单校验规则
const rules = ref({
  username: [
    { required: true, message: "请输入登录用户名", trigger: 'blur' },
    { min: 3, max: 18, message: '用户名长度需在3-18位字符之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的字符',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的字符',
      trigger: 'blur'
    }
  ]
})

// 当点击表单以外的其他区域时弹出一个确认框
const handleClose = () => {
  ElMessageBox.confirm('你确定要关闭这个窗口吗?')
    .then(() => {
      drawer.value = false // 关闭抽屉
      emit('success')
    })
    .catch(() => {
      // catch error
    })
}

// 提交登录表单
const emit = defineEmits(['success'])
const onSubmit = async () => {
  // console.log(await form.value.validate());
  await form.value.validate()
  const { data } = await registerUser(registerForm.value)
  // console.log(data);
  if (data.code === 200) {
    ElMessage({
      type: "success",
      message: '注册用户成功!'
    })
  }
  drawer.value = false // 关闭抽屉
  emit('success');
}

</script>
<template>
  <!-- 抽屉 -->
  <!-- <el-drawer v-model="drawer" :before-close="handleClose" title="登录" :with-header="true" :show-close="false"> -->
  <el-dialog v-model="drawer" :show-close="false" title="登录" width="30%" :before-close="handleClose">
    <!-- form表单 -->
    <el-form :model="registerForm" :rules="rules" ref="form" autocomplete="off" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="二次密码" prop="repassword">
        <el-input type="password" v-model="registerForm.repassword" placeholder="请再次输入密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">创建</el-button>
        <el-button @click="emit('success')">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style>
</style>
